package com.leonzx.base.service.mail;

import com.leonzx.base.dao.email.*;
import com.leonzx.base.dao.system.BaseFileDAO;
import com.leonzx.base.entity.email.*;
import com.leonzx.base.entity.system.BaseFile;
import com.leonzx.base.service.BaseService;
import com.leonzx.base.service.file.FileUploadService;
import com.leonzx.base.service.system.BaseFileService;
import com.leonzx.base.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;

/**
 * @Author:chen
 * @Description:
 * @Date: 2018-07-09 14:35
 */
@Service
public class MailHistoryService extends BaseService {

    @Autowired
    private UserMailDAO userMailDAO;
    @Autowired
    private MailFileDAO mailFileDAO;
    @Autowired
    private MailAddresseeDAO mailAddresseeDAO;
    @Autowired
    private MailCopyDAO mailCopyDAO;
    @Autowired
    private MailHistoryDAO mailHistoryDAO;
    @Autowired
    private BaseFileDAO baseFileDAO;
    @Autowired
    private UserMailDAO userMailDao;
    @Autowired
    private BaseFileService baseFileService;
    @Autowired
    private FileUploadService fileUploadSerivce;


    /**
     * 邮件发送
     *
     * @Author chen
     * @Date 2018/7/12 12:12
     */
    @Transactional
    public void sendEmail(MailHistory mailHistory, String userId, HttpServletRequest request, HttpServletResponse response) {
        String mailUserIds = mailHistory.getMailUserIds();
        String mails = mailHistory.getMails();
        String copyUserIds = mailHistory.getCopyUserIds();
        String copyMails = mailHistory.getCopyMails();
        String fileIds = mailHistory.getFileIds();
        List<String> imgs = HtmlUtils.getImageSrc(mailHistory.getContent());
        List<Map<String, String>> urlMaps = getUetitorImgs(imgs, "0",request, response);//返回全路径
        List<Map<String, String>> imgUrls = getUetitorImgs(imgs, "1",request, response);//返回保存路径
        String content = replaceContentScrImgId(mailHistory.getContent(), imgUrls);
        String[] addMails = null;
        String[] addCopyMails = null;
        List<String> fIds = new ArrayList<>();
        List<String> serviceFilePaths = new ArrayList<>();
        if (StringUtils.isNotBlank(mails)) {
            addMails = mails.split(",");
        }
        if (StringUtils.isNotBlank(copyMails)) {
            addCopyMails = copyMails.split(",");
        }
        if (StringUtils.isNotBlank(fileIds)) {
            fIds = Arrays.asList(fileIds.split(","));
            List<String> filePaths = baseFileDAO.findByIds(fIds);
            for (int i = 0; i < filePaths.size(); i++) {
                String serviceFilePath = request.getSession().getServletContext().getRealPath(filePaths.get(i));
                serviceFilePaths.add(serviceFilePath);
            }
        }
        UserMail userMail = userMailDao.findByUserId(userId);
        //发送邮件
        boolean flag = JavaMailUtil.sendMail(userMail.getLogin(), userMail.getPassword(), userMail.getMail(), addMails, addCopyMails,
                mailHistory.getTitle(), content, serviceFilePaths, urlMaps, userMail.getMailService());
        if (flag) {
            //保存邮件发送历史表
            mailHistory.setCreateUserId(userId);
            mailHistory.setCreateTime(new Date());
            mailHistory.setId(UUIDUtils.getUUID());
            mailHistory.setSenderUserId(userId);
            mailHistoryDAO.insert(mailHistory);

            //邮件发送成功后，将正文中图片发送至oss
            List<String> baseFileIds = uoloadImg(imgUrls, userId, request, response);
            if(fIds != null && fIds.size() > 0){
                baseFileDAO.updateTypeByIds(fIds, Constants.BASE_FILE_Y);
            }
           if(baseFileIds != null && baseFileIds.size() > 0){
               baseFileDAO.updateTypeByIds(baseFileIds, Constants.BASE_FILE_Y);
           }
            //保存邮件与附件对应关系
            saveMailFile(baseFileIds, userId, mailHistory.getId());
            saveMailFile(fIds, userId, mailHistory.getId());
            //保存邮件对应收件人
            if (StringUtils.isNotBlank(mailUserIds)) {
                String[] mIds = mailUserIds.split(",");
                for (int i = 0; i < mIds.length; i++) {
                    MailAddressee mailAddressee = new MailAddressee();
                    mailAddressee.setId(UUIDUtils.getUUID());
                    mailAddressee.setMailHistoryId(mailHistory.getId());
                    mailAddressee.setCreateTime(new Date());
                    mailAddressee.setCreateUserId(userId);
                    mailAddressee.setAddresseeUserId(mIds[i]);
                    mailAddresseeDAO.insert(mailAddressee);
                }
            }

            //保存邮件对应的抄送人
            if (StringUtils.isNotBlank(copyUserIds)) {
                String[] cIds = copyUserIds.split(",");
                for (int i = 0; i < cIds.length; i++) {
                    MailCopy mailCopy = new MailCopy();
                    mailCopy.setId(UUIDUtils.getUUID());
                    mailCopy.setCreateUserId(userId);
                    mailCopy.setCreateTime(new Date());
                    mailCopy.setMailHistoryId(mailHistory.getId());
                    mailCopy.setCopyUserId(cIds[i]);
                    mailCopyDAO.insert(mailCopy);
                }
            }

            //删除oss上的附件
            List<BaseFile> baseFiles = baseFileDAO.findByType(Constants.BASE_FILE_N);
            if (baseFiles != null && baseFiles.size() > 0) {
                for (int i = 0; i < baseFiles.size(); i++) {
                    BaseFile b = baseFiles.get(i);
                    fileUploadSerivce.delete(b.getServiceFilePath() + File.separator + b.getNewFileName());
                    String edFilePath = request.getSession().getServletContext().getRealPath(b.getServiceFilePath());
                    FileUtils.deleteFile(edFilePath);
                }
            }
            //删除本地所有邮件附件
            File file = new File(File.separator + Constants.FILE_TYPE_EMAIL_FILE);
            FileUtils.deleteAllFilesOfDir(file);
        }
    }

    /**
     * 处理得到的html中img的src，因为得到的一些url可能是网络图片不需要处理，所以剔除,并生成邮件正文中图片对应的唯一id
     *
     * @Author chen
     * @Date 2018/7/12 15:58
     */
    public List<Map<String, String>> getUetitorImgs(List<String> imgs, String type,HttpServletRequest request, HttpServletResponse response) {
        List<Map<String, String>> urlMaps = new ArrayList<>();
        if (imgs != null && imgs.size() > 0) {
            for (int i = 0; i < imgs.size(); i++) {
                if (imgs.get(i).indexOf("ueditor/") != -1) {
                    Map<String, String> map = new HashMap<>();
                    String allPath = imgs.get(i);
                    if("0".equals(type)){
                        allPath = request.getSession().getServletContext().getRealPath(imgs.get(i));

                    }
                    map.put("imgId" + i, allPath);
                    urlMaps.add(map);
                }
            }
        }
        return urlMaps;
    }

    /**
     * 将图片上传至oss中，且保存附件表
     *
     * @Author chen
     * @Date 2018/7/12 16:31
     */
    @Transactional
    public List<String> uoloadImg(List<Map<String, String>> imgUrls, String userId, HttpServletRequest request, HttpServletResponse response) {
        List<String> baseFileIds = new ArrayList<>();
        for (int i = 0; i < imgUrls.size(); i++) {
            Map<String, String> map = imgUrls.get(i);
            for (String key : map.keySet()) {
                String path = request.getSession().getServletContext().getRealPath(map.get(key));
                File file = new File(path);
                String oldName = file.getName();
                int index = oldName.lastIndexOf(".");
                //判断是否已经生成过
                String uuId = UUIDUtils.getUUID();
                String newName = uuId + oldName.substring(index); //新文件名
                String savePath = Constants.FILE_QZ + File.separator + Constants.FILE_TYPE_EMAIL_FILE + File.separator + newName;
                FileInputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(file);
                    MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
                    fileUploadSerivce.upload(multipartFile, savePath);
                    BaseFile baseFile = baseFileService.saveBaseFile(newName, oldName, map.get(key), userId, Constants.FILE_QZ, Constants.FILE_TYPE_EMAIL_FILE, Constants.BASE_FILE_N);
                    FileUtils.deleteFile(map.get(key));
                    baseFileIds.add(baseFile.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return baseFileIds;
    }

    /**
     * 生成html中对应scr的id
    *@Author chen
    *@Date 2018/7/13 13:43
    */
    public String replaceContentScrImgId(String content, List<Map<String, String>> imgUrls){
        if(imgUrls != null && imgUrls.size() > 0) {
            for (int i = 0; i < imgUrls.size(); i++) {
                Map<String, String> map = imgUrls.get(i);
                for (String key : map.keySet()) {
                    content = content.replaceAll(map.get(key), "cid:" + key);
                }
            }
        }
        return content;
    }

    @Transactional
    public void saveMailFile(List<String> fIds, String userId, String mailHistoryId){
        if (fIds != null && fIds.size() > 0) {
            for (int i = 0; i < fIds.size(); i++) {
                MailFile mailFile = new MailFile();
                mailFile.setId(UUIDUtils.getUUID());
                mailFile.setCreateTime(new Date());
                mailFile.setCreateUserId(userId);
                mailFile.setMailHistoryId(mailHistoryId);
                mailFile.setFileId(fIds.get(i));
                mailFileDAO.insert(mailFile);
            }
        }
    }

    /**
     * 查询所有邮件信息
    *@Author chen
    *@Date 2018/7/13 15:24
    */
    public List<MailHistory> findAllMailHistory(MailHistory mailHistory){
        return mailHistoryDAO.findAll(mailHistory);
    }

    /**
     * 查询邮件详细信息
    *@Author chen
    *@Date 2018/7/16 14:29
    */
    public MailHistory findMailDetailByHistoryId(String id){
        MailHistory mailHistory = mailHistoryDAO.findById(id);
        List<MailCopy> mailCopies = mailCopyDAO.findByCopyUserByHistoryId(id);
        List<MailAddressee> mailAddressees = mailAddresseeDAO.findAddresseeByHistoryId(id);
        mailHistory.setMailCopies(mailCopies);
        mailHistory.setMailAddressees(mailAddressees);
        List<MailFile> mailFiles = mailFileDAO.findMailFileByHistoryId(id);
        String content = mailHistory.getContent();
        if(mailFiles != null && mailFiles.size() > 0){
            for (int i = 0; i < mailFiles.size(); i++) {
                MailFile mailFile = mailFiles.get(i);
                content = content.replace(mailFile.getServiceFilePath(), mailFile.getFilepath());
            }
            mailHistory.setMailFiles(mailFiles);
        }
        mailHistory.setContent(content);

        return mailHistory;
    }
}
